package pe.com.rimac.portal.tag;

import java.util.MissingResourceException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.portlet.PortletConfig;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

public class PortletBaseTag extends TagSupport 
{
    private static Logger logger = Logger.getLogger(PortletBaseTag.class.getName());
    
    /**
     * @return
     * @throws JspException
     */
    protected RenderRequest getRenderRequest() throws JspException
    {
        Object obj = this.pageContext.getAttribute("renderRequest");
        if (obj == null || !(obj instanceof RenderRequest))
        {
            throw new JspException("No se pudo obtener el render request.");
        }
        return (RenderRequest) obj;
    }

    /**
     * @return
     * @throws JspException
     */
    protected RenderResponse getRenderResponse() throws JspException
    {
        Object obj = this.pageContext.getAttribute("renderResponse");
        if (obj == null || !(obj instanceof RenderResponse))
        {
            throw new JspException("No se pudo obtener el render response.");
        }
        return (RenderResponse) obj;
    }
    
    protected PortletConfig getPortletConfig() throws JspException
    {
        Object obj = this.pageContext.getAttribute("portletConfig");
        if (obj == null || !(obj instanceof PortletConfig))
        {
            throw new JspException("No se pudo obtener el portlet config.");
        }
        return (PortletConfig) obj;
    }
    
    protected String getMessage(String key, String defaultMessage)
    {
        String message = defaultMessage;
        try
        {
            message = getPortletConfig().getResourceBundle(getRenderRequest().getLocale()).getString(key);
        }
        catch (JspException e)
        {
            logger.log(Level.WARNING, "Error looking up '" + key + "' from message bundle, using default.", e);
        }
        catch (MissingResourceException e)
        {
            logger.log(Level.WARNING, "No message for key '" + key + "', using default.");
        }
        return message;
    }
}